import os
from datetime import datetime

from enetity_extraction.json_result import generate_return_json


def split_number(number):
    # 第一个部分
    # part1 = number[0:6]
    part1 = number[1:5]

    # 检查number[6]是否为汉字
    if not ('\u4e00' <= number[6] <= '\u9fff'):
        return False, False, False, False

    # 找到number[6]后的第一个数字串
    index_digit = 7
    while number[index_digit].isdigit():
        index_digit += 1

    # 第二个部分
    part2 = number[6:index_digit]

    # 第三个部分
    part3_start = index_digit
    part3_end = part3_start
    while not number[part3_end].isdigit() and part3_end < len(number):
        part3_end += 1
    part3 = number[part3_start:part3_end]

    # 第四个部分
    part4 = number[part3_end:]

    return part1, part2, part3, part4


def check_case_code(court_codes, type_codes, data_dic):
    result = generate_return_json()

    if data_dic['案号'] == {}:
        # print('案号错误')
        result['type'] = '案号缺失或错误'
        return result
        # return None

    data_str = data_dic['案号']['match']
    # result赋值
    result['paragraph_index'] = data_dic['案号']['paragraph_index']
    result['start'] = data_dic['案号']['start_pos']
    result['end'] = data_dic['案号']['end_pos']
    result['offset'] = data_dic['案号']['end_pos'] - data_dic['案号']['start_pos'] + 1

    year, region, case_type, case_number = split_number(data_str)

    if not year:
        result['type'] = '案号不合法'
        return result

    # [r"\s*[（|(][0-9]+[)|）].{,7}[初|终][0-9]+号\s*$"]
    # pattern = r'（(\d{4})）([\u4e00-\u9fa5]\d{4})([\u4e00-\u9fa5]+)(\d+号)'
    # match = re.match(pattern, data_str)
    # if match:
    #     # 提取各个捕获组
    #     year, region, case_type, case_number = match.groups()
    # else:
    #     # print('案号不合法')
    #     result['type'] = '案号不合法'
    #     return result

    # 判断年份是否合法
    try:
        datetime(int(year), 1, 1)

    except ValueError:
        result['type'] = '案号的年份不合法'
        return result

    # 判断年份是否大于当前年份
    current_year = datetime.now().year
    if int(year) > current_year:
        # print('案号的年份不合法')
        result['type'] = '案号的年份不合法'
        return result

    # 判断法院代字是否在库里面
    if region not in court_codes:
        # print('案号的法院代字不合法')
        result['type'] = '案号的法院代字不合法'
        return result

    # 判断类型代字是否在库里面
    if case_type not in type_codes:
        # print('案号的类型代字不合法')
        result['type'] = '案号的类型代字不合法'
        return result

    result['type'] = '案号合法'
    # return result
    # return None


def create_type_codes():
    type_codes = set()  # 初始化全局集合

    # 获取当前工作目录的上级目录
    current_dir = os.getcwd()
    parent_dir = os.path.dirname(current_dir)

    # 定义可能的目录列表
    possible_dirs = [
        current_dir,  # 当前工作目录
        parent_dir  # 上级目录
    ]

    file_found = False
    file_path = ''

    # 遍历目录列表，查找文件
    for directory in possible_dirs:
        potential_path = os.path.join(directory, 'logic_rule', 'data', 'all_type_code.txt')
        if os.path.isfile(potential_path):
            file_path = potential_path
            file_found = True
            break

    if not file_found:
        raise FileNotFoundError("文件'all_type_code.txt'无法在指定文件目录下找到。")

    # 读取文件并填充集合
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                line = line.strip()
                type_codes.add(line)
    except Exception as e:
        raise RuntimeError(f"Error reading the file '{file_path}': {e}")

    # 调用函数前，打印当前工作目录
    # print(f"Current working directory: {os.getcwd()}")
    return type_codes


if __name__ == "__main__":
    pass
